package com.ugoodtech.mdcc.core.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.DepartmentRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.core.service.GetDepartmentNameForSendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GetDepartmentNameForSendServiceImpl implements GetDepartmentNameForSendService {

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 获取用户的一级部门
     *
     * @param user
     * @return
     */
    @Override
    public String getUserDepartmentName(User user) {
        StringBuilder departmentStr = new StringBuilder();
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (null == userProfile) {
            return departmentStr.toString();
        }
        List<Department> departmentList = userProfile.getDepartmentList();
        if (user.getUserType().equals(UserType.dealers)) {
            if (!departmentList.isEmpty() && null != departmentList.get(0)) {
                Department department = departmentList.get(0);
                departmentStr.append(department.getTotalName());
            }
        } else {
            List<Long> departmentListId = getParentDepartment();
            for (Department department : departmentList) {
                if (departmentListId.contains(department.getId())) {
                    departmentStr.append(department.getTotalName()).append(",");
                }
            }
        }
        return departmentStr.toString();
    }

    private List<Long> getParentDepartment() {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.enabled.eq(true));
        builder.and(qDepartment.parent.isNotNull());
        List<Department> departmentList = (List<Department>) departmentRepository.findAll(builder);
        List<Long> departmentListId = new ArrayList<>();
        for (Department department : departmentList) {
            departmentListId.add(department.getId());
        }
        return departmentListId;
    }
}
